# api/routes/qa.py
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import Optional, List
from services.qa_service import ask_question_service

router = APIRouter(prefix="/api/v1", tags=["问答系统"])

class QuestionRequest(BaseModel):
    question: str

class AnswerResponse(BaseModel):
    answer: str
    sources: List[str]
    risk_disclaimer: Optional[str] = None

@router.get("/")
async def root():
    """根路径，用于健康检查"""
    return {"message": "金融问答系统API服务运行中", "status": "healthy"}

@router.post("/ask", response_model=AnswerResponse)
async def ask_question(request: QuestionRequest):
    """问答接口"""
    try:
        response = ask_question_service(request.question)
        return AnswerResponse(
            answer=response.get('answer', ''),
            sources=response.get("sources", []),
            risk_disclaimer=response.get("risk_disclaimer", "")
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"处理问题时出错: {str(e)}")

@router.get("/health")
async def health_check():
    """健康检查接口"""
    from services.qa_service import is_rag_chain_ready
    return {
        "status": "healthy",
        "rag_chain": "ready" if is_rag_chain_ready() else "not ready"
    }
